Hi,
I have a table EmployeeHierarchy with EmployeeID and
ManagerID. I need to write a recursive query to get the hierarchy of employees. Any suggestions?
home / developersection / forums / help with writing a recursive query in sql server
Hi,
I have a table EmployeeHierarchy with EmployeeID and
ManagerID. I need to write a recursive query to get the hierarchy of employees. Any suggestions?
Ravi Vishwakarma
16-Jul-2024Recursive queries in SQL Server are typically written using Common Table Expressions (CTEs). These are particularly useful for hierarchical data, such as organizational charts, family trees, or any dataset that has a parent-child relationship.
Here's a basic example to illustrate how to write a recursive query using a CTE in SQL Server. We'll use a hypothetical organizational structure as an example.
Example: Organizational Hierarchy
Assume we have a table named
Employeeswith the following structure:In this table:
EmployeeIDis the unique identifier for each employee.EmployeeNameis the name of the employee.ManagerIDis theEmployeeIDof the employee's manager. The top-level manager (Alice) has aNULLManagerID.Recursive Query
Retrieve the entire hierarchy starting from the top-level manager.
Here's how you can write a recursive CTE to achieve this:
Explanation:
Anchor Member:
SELECTstatement in the CTE defines the anchor member, which retrieves the top-level manager(s) (those withNULLManagerID).Recursive Member:
SELECTstatement in the CTE joins theEmployeestable with theEmployeeCTEonManagerIDandEmployeeID, effectively retrieving the employees managed by each employee in theEmployeeCTE.Levelis incremented by 1 to indicate the hierarchy level.Final SELECT:
SELECTstatement retrieves the data from the CTE, and theORDER BYclause is used to sort the results by hierarchy level andEmployeeID.This recursive query will produce the hierarchical structure of the organization, starting from the top-level manager down to the lowest level.
Read more
Define the PIVOT Table with examples in the SQL server.
Explain the SQL triggers and their uses
Explain the SQL Server backups and their types